//
//  MIDIYuedongtwoController.m
//  迷笛
//
//  Created by . on 2018/9/17.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIYuedongtwoController.h"
#import "MIDIissueController.h"
#import "MIDIYuedongCell.h"
#import "MIDIcommController.h"
#import "MIDIyuedongmodel.h"

@interface MIDIYuedongtwoController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSArray * arr;
}
@property(nonatomic,strong)UITableView * Hottable;
@property(nonatomic,strong)UIButton * btn1;
@property(nonatomic,copy)NSString *detailsapi;
@property(nonatomic,strong)NSMutableArray * yuedongArr;

@property(nonatomic,copy)NSString * praiseapi;
@property(nonatomic,copy)NSString * apptoken;
@property(nonatomic,copy)NSString * followapi;


@end

@implementation MIDIYuedongtwoController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];
    
//    [self detailsRequest];
//    self.yuedongArr = [NSMutableArray array];
    
    
//    self.view.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(Block:)];
   
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"后退"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    [self homeUI];
    
}
-(void)praiseRequest
{
   
}

-(void)detailsRequest
{
    NSString * page = @"1";
    
    self.detailsapi = [NSString stringWithFormat:@"%@circle/dynamic/%@?page=%@&token=%@",MIDIApiRoot,self.ID,page,_apptoken];
    NSLog(@"圈子详情接口%@",self.detailsapi);
    
    
    [EdHttp get:self.detailsapi params:nil progress:^(id downloadProgress) {
        
    }
        success:^(id responseObject)
    {
        NSLog(@"圈子详情%@",responseObject);
        NSArray *arr4 = responseObject[@"data"];
        NSArray *arr5 = responseObject[@"resource"];

        for (NSDictionary *dic5 in arr5)
        {
            NSString * path;

            if (![dic5[@"path"] isKindOfClass:[NSNull class]])
            {
                path = dic5[@"path"];
            }
        }
        
        for (NSDictionary *dic4 in arr4)
        {
            NSDictionary * user;
            
            NSString * name;
            NSString * avatar;
            NSString * comments;
            NSString * collects;
            NSString * date;
            NSString * title;
            NSString * user_id;
            if (![dic4[@"title"] isKindOfClass:[NSNull class]])
            {
                title = dic4[@"title"];
            }
            if (![dic4[@"date"] isKindOfClass:[NSNull class]])
            {
                date = dic4[@"date"];
            }
            
            
            if (![dic4[@"comments"] isKindOfClass:[NSNull class]])
            {
                comments = dic4[@"comments"];
            }
            if (![dic4[@"collects"] isKindOfClass:[NSNull class]])
            {
                collects = dic4[@"collects"];
            }

            if (![dic4[@"user"] isKindOfClass:[NSNull class]])
            {
                user = dic4[@"user"];
            }
            
            if (![dic4[@"title"] isKindOfClass:[NSNull class]])
            {
                title = dic4[@"title"];
            }
            if (![user[@"nickname"] isKindOfClass:[NSNull class]])
            {
                name = user[@"nickname"];
            }
            else
            {
                name = @"";
            }
            if (![user[@"avatar"] isKindOfClass:[NSNull class]])
            {
                avatar = user[@"avatar"];
            }
            else
            {
                avatar = @"";
            }
            if (![user[@"user_id"] isKindOfClass:[NSNull class]])
            {
                user_id = user[@"user_id"];
            }
            
            

            MIDIyuedongmodel * mmact = [MIDIyuedongmodel new];
            mmact.title = title;
            mmact.name = name;
            mmact.avatar =avatar;
            mmact.comments = comments;
            mmact.collects = collects;
            mmact.path =page;
            mmact.date =date;
            mmact.user_id = user_id;
            
            
            
            
            
//            动态id
            mmact.modelId = dic4[@"id"];
//            状态id
            mmact.iscollectionId = dic4[@"is_collection"];
            mmact.is_follow = dic4[@"is_follow"];
//            mmact.title = title;
            [self.yuedongArr addObject:mmact];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.Hottable reloadData];
            
        });
    }
        failure:^(NSError *error)
    {
        NSLog(@"失败");
    }];
    
  
}
//关注用户
-(void)followRequest
{
   
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    if (section == 0)
    {
        return 1;
    }
    if (section ==1)
    {
        return self.yuedongArr.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * cellID = @"cell";
//    MIDIYuedongCell * cell =[tableView dequeueReusableCellWithIdentifier:cellID];
    MIDIYuedongCell * cell =[tableView dequeueReusableHeaderFooterViewWithIdentifier:cellID];

    if (!cell)
    {
        cell = [[MIDIYuedongCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.backgroundColor = [UIColor colorWithHexString:@"#1B212F"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }

    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
//            MIDIyuedongmodel * mm2 = _yuedongArr[indexPath.row];
            

            [cell.headimage sd_setBackgroundImageWithURL:self.cover forState:0];

//            [cell.headimage setBackgroundImage:[UIImage imageNamed:@"IMG_0195.jpg"] forState:0];
            cell.name.text = self.name;
            cell.Focus.text = [NSString stringWithFormat:@"关注%@",self.fans];
            cell.TZ.text = [NSString stringWithFormat:@"帖子数%@",self.TZ];
            cell.XX.backgroundColor =[UIColor blackColor];
            cell.titleIntroduction.text = @"本圈简介";
            cell.Introduction.text = self.intro;
//            cell.number.hidden=YES;

        }
    }
    if (indexPath.section == 1)
    {
        
        MIDIyuedongmodel * mm1 = self.yuedongArr[indexPath.row];
        [cell.headimage1 sd_setBackgroundImageWithURL:mm1.avatar forState:0];
        cell.Name.text = mm1.name;
        
        
        if ([mm1.is_follow isEqualToNumber:@1])
        {
            [cell.foucus setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
            [cell.foucus setTitle:@"已关注" forState:UIControlStateNormal];
            cell.foucus.tag = indexPath.row;
            cell.foucus.selected = NO;
            [cell.foucus addTarget:self action:@selector(Foucus:) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            [cell.foucus setTitle:@"关注" forState:UIControlStateNormal];
            [cell.foucus setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
            cell.foucus.tag = indexPath.row;
            cell.foucus.selected = YES;
            [cell.foucus addTarget:self action:@selector(Foucus:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        
        
        
        cell.conunt.text = mm1.title;
            
        
        [cell.iamgeg1 sd_setImageWithURL:[NSURL URLWithString:mm1.path] placeholderImage:nil];
        [cell.iamgeg2 sd_setImageWithURL:[NSURL URLWithString:mm1.path] placeholderImage:nil];
        [cell.iamgeg3 sd_setImageWithURL:[NSURL URLWithString:mm1.path] placeholderImage:nil];

        
        cell.commtext.text = mm1.comments;
        
        [cell.comm setBackgroundImage:[UIImage imageNamed:@"pinglun"] forState:0];
        [cell.comm addTarget:self action:@selector(commbtn:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.number.text = mm1.collects;
        
        if ([[self.yuedongArr[indexPath.row] iscollectionId] isEqualToNumber:@1])
        {
            
        [cell.love setBackgroundImage:[UIImage imageNamed:@"xuanzhong-xin"] forState:0];
        cell.love.tag = indexPath.row;
        [cell.love addTarget:self action:@selector(lovebtn:) forControlEvents:UIControlEventTouchUpInside];
        cell.love.selected = NO;
        }
        else
        {
            [cell.love setBackgroundImage:[UIImage imageNamed:@"xin"] forState:0];
            cell.love.tag = indexPath.row;
            [cell.love addTarget:self action:@selector(lovebtn:) forControlEvents:UIControlEventTouchUpInside];
            cell.love.selected = YES;
        }
        
        
//        [cell.love addTarget:self action:@selector(lovebtn:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.daytime.text = mm1.date;

    }
    return cell;
}

-(void)commbtn:(UIButton *)sender
{
    
    CGPoint point = sender.center;
    point = [self.Hottable convertPoint:point fromView:sender.superview];
    NSIndexPath* indexpath = [self.Hottable indexPathForRowAtPoint:point];
    NSLog(@"第%ld行Cell",(long)indexpath.row);
    
    MIDIcommController * com =[[MIDIcommController alloc]init];
    
    MIDIyuedongmodel *model = self.yuedongArr[indexpath.row];

    NSNumber *yuedongID = model.modelId;
    
    NSNumber * praiseID = model.iscollectionId;
//    NSNumber *typeNumber = [self.yuedongArr[sender.tag] modelId];

//动态id
    com.ID = yuedongID;
//状态id
    com.praiseID = praiseID;
    
    [self.navigationController pushViewController:com animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1.0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- ( UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(void)Foucus:(UIButton * )sender
{

    NSString *userid = [self.yuedongArr[sender.tag] user_id];
    
    
    self.followapi = [NSString stringWithFormat:@"%@users/follow?user_id=%@&token=%@",MIDIApiRoot,userid,_apptoken];
    
    if (sender.selected == YES)
    {
        [EdHttp get:self.followapi params:nil progress:^(id downloadProgress) {

        }
            success:^(id responseObject)
        {
            NSLog(@"关注成功%@",responseObject);
            sender.selected=!sender.selected;//每次点击都改变按钮的状态

            if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
            {
                //第一次点击为蓝色（关注）
                MIDIyuedongmodel *model = self.yuedongArr[sender.tag];
                model.is_follow = @1;
                [sender setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
                [sender setTitle:@"已关注" forState:UIControlStateNormal];
                [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                
                [self detailsRequest];
                self.yuedongArr = [NSMutableArray array];

                
                [SVProgressHUD showSuccessWithStatus:@"关注成功"];
                [SVProgressHUD dismissWithDelay:1.0];
                NSLog(@"已关注");
            }
        }
            failure:^(NSError *error)
        {
            NSLog(@"失败");
        }];
    }
    else
    {
        UIAlertController *controller=[UIAlertController alertControllerWithTitle:@"确认不再关注此人？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *act1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {
            
        }];
        [act1 setValue:[UIColor colorWithHexString:@"#171717"] forKey:@"titleTextColor"];
        
        UIAlertAction *act2=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
        {

            [EdHttp get:self.followapi params:nil progress:^(id downloadProgress) {
                
            }
                success:^(id responseObject)
             {
                 NSLog(@"取消成功%@",responseObject);
                 sender.selected=!sender.selected;//每次点击都改变按钮的状态
                 
                 if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
                 {
                     //第一次点击为蓝色（关注）
                     MIDIyuedongmodel *model = self.yuedongArr[sender.tag];
                     model.is_follow = @0;
                     
                     [sender setTitle:@"关注" forState:UIControlStateNormal];
                     
                     [sender setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];

                     [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                     [self detailsRequest];
                     self.yuedongArr = [NSMutableArray array];
                     [SVProgressHUD showSuccessWithStatus:@"取消成功"];
                     [SVProgressHUD dismissWithDelay:1.0];
                 }
             }
                failure:^(NSError *error)
             {
                 NSLog(@"失败");
             }];
            NSLog(@"取消关注");
            
        }];
        
        [act2 setValue:[UIColor colorWithHexString:@"#FF005D"] forKey:@"titleTextColor"];
        [controller addAction:act1];
        [controller addAction:act2];
        [self presentViewController:controller animated:YES completion:^{
            
        }];
        
    }
}
-(void)lovebtn:(UIButton * )sender
{
//    动态id
    NSNumber *typeNumber = [self.yuedongArr[sender.tag] modelId];

    self.praiseapi = [NSString stringWithFormat:@"%@circle/dynamic/collect/%@?token=%@",MIDIApiRoot,typeNumber,_apptoken];

    if (sender.selected == YES)
    {
       
        CGPoint point = sender.center;
        point = [self.Hottable convertPoint:point fromView:sender.superview];
        NSIndexPath* indexpath = [self.Hottable indexPathForRowAtPoint:point];
        NSLog(@"第%ld行Cell",(long)indexpath.row);

            [EdHttp get:self.praiseapi params:nil progress:^(id downloadProgress)
             {
                 
             }
                success:^(id responseObject)
             {
                 if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
                 {
                     sender.selected=!sender.selected;//每次点击都改变按钮的状态

                     MIDIYuedongCell *selCell = [self.Hottable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:1]];
                     MIDIyuedongmodel *selModel = self.yuedongArr[sender.tag];
                     NSString *origenAttentionNum = selModel.collects;
                     selModel.collects = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] + 1];
                     selCell.number.text = [NSString stringWithFormat:@"%@",selModel.collects];
                     
                     MIDIyuedongmodel *model = self.yuedongArr[sender.tag];
                     model.iscollectionId = @1;

                     
                     [sender setBackgroundImage:[UIImage imageNamed:@"xuanzhong-xin"] forState:0];
                     [SVProgressHUD showSuccessWithStatus:@"点赞成功"];
                     [SVProgressHUD dismissWithDelay:1.0];

                     NSLog(@"点赞成功%@",responseObject);
                 }
                 
             }
                failure:^(NSError *error)
             {
                 NSLog(@"失败");
             }];
            NSLog(@"已关注");

    }
    else
    {

        [EdHttp get:self.praiseapi params:nil progress:^(id downloadProgress)
         {
             
         }
            success:^(id responseObject)
         {
             if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
             {
                 
                 
                 sender.selected=!sender.selected;//每次点击都改变按钮的状态
                 MIDIYuedongCell *selCell = [self.Hottable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:sender.tag inSection:1]];
                 MIDIyuedongmodel *selModel = self.yuedongArr[sender.tag];
                 NSString *origenAttentionNum = selModel.collects;
                 selModel.collects = [NSString stringWithFormat:@"%ld",[origenAttentionNum integerValue] - 1];
                 selCell.number.text = [NSString stringWithFormat:@"%@",selModel.collects];
                 MIDIyuedongmodel *model = self.yuedongArr[sender.tag];
                 model.iscollectionId = @0;
                 [sender setBackgroundImage:[UIImage imageNamed:@"xin"] forState:0];
                 [SVProgressHUD showSuccessWithStatus:@"取消成功"];
                 [SVProgressHUD dismissWithDelay:1.0];

                 NSLog(@"取消成功%@",responseObject);
             }
             
         }
            failure:^(NSError *error)
         {
             NSLog(@"失败");
         }];
        

        
        
    }
}
// 返回上一级
-(void)Block:(UIButton * )sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    
    [self detailsRequest];
    self.yuedongArr = [NSMutableArray array];

    
    self.tabBarController.tabBar.hidden = YES;

    self.navigationController.navigationBar.translucent = NO;//Bar的模糊效果，默认为YES

    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#171717"];
    self.title = @"乐动圈";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"],NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:WidthScale(17)]}];
    //    去掉导航黑线
    UIImage *img = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:img  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}
-(void)homeUI
{
    [self.view addSubview:self.Hottable];
    [self.view addSubview:self.btn1];
    [self.btn1 mas_makeConstraints:^(MASConstraintMaker *make)
     {
         make.bottom.mas_offset(WidthScale(-80));
         make.right.mas_offset(WidthScale(-20));
         make.width.mas_offset(WidthScale(60));
         make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(60):HeightScale(60));
     }];
}
-(UIButton *)btn1
{
    if (!_btn1)
    {
        _btn1 =[[UIButton alloc]init];
        [_btn1 setBackgroundImage:[UIImage imageNamed:@"floatBar"] forState:0];
        [_btn1 addTarget:self action:@selector(newbtn:) forControlEvents:UIControlEventTouchUpInside];
      
    }
    return _btn1;
}
-(void)newbtn:(UIButton *)sender
{
    MIDIissueController * foud =[[MIDIissueController alloc]init];
    
    foud.cirlcleID = self.ID;
    
    [self.navigationController pushViewController:foud animated:YES];
}

-(UITableView *)Hottable
{
    if (!_Hottable)
    {
        _Hottable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kDevice_Is_iPhoneX?HeighX(600):HeightScale(620)) style:UITableViewStyleGrouped];
        _Hottable.dataSource = self;
        _Hottable.delegate = self;
//        1B212F
        _Hottable.backgroundColor = [UIColor blackColor];
        _Hottable.separatorStyle = UITableViewCellSeparatorStyleNone;
        

    }
    return _Hottable;
}
@end
